package com.bsh.serviceImpl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bsh.mybatis.model.Message;
import com.bsh.repository.DaoMessage;
import com.bsh.service.MessageService;
import com.bsh.utils.Pager;
import com.bsh.utils.jpush.JpushMessage;
import com.bsh.utils.jpush.JpushMessageSender;
import com.bsh.utils.jpush.JpushMessageType;
import com.mysql.jdbc.StringUtils;

/**
 * 系统消息
 * @author gsh
 *
 */
@Service
@Transactional
public class MessageServiceImpl implements MessageService {
	@Autowired
	private DaoMessage messageDao;
	@Autowired
	JpushMessageSender jmsg;
	
	@Override
	public List<Map<String, Object>> getPage(Pager pager,String title) {
		StringBuilder sb =new StringBuilder();
		if(!StringUtils.isNullOrEmpty(title))
			sb.append(String.format(" and a.title = '%s' ",title.trim()));	
		List<Map<String, Object>> list = messageDao.getPage(pager,sb.toString());
		return list;
	}	

	@Override
	public Message getMessage(Integer id) {
		return messageDao.selectByPrimaryKey(id);
	}

	@Override
	public Integer addMessage(Message image) {
		image.setCreateTime(new Date());
		image.setStatus((short)0);
		return messageDao.insert(image);
	}

	@Override
	public Integer editMessage(Message image) {
		Message imgOld = messageDao.selectByPrimaryKey(image.getId());
		imgOld.setTitle(image.getTitle());
		imgOld.setContent(image.getContent());
		return messageDao.updateByPrimaryKey(imgOld);
	}

	@Override
	public Integer publish(int id, boolean isEnabele) {
		Message imgOld = messageDao.selectByPrimaryKey(id);
		imgOld.setStatus((short)(isEnabele?1:0));
		int res = messageDao.updateByPrimaryKey(imgOld);
		if(isEnabele && res>0){
			JpushMessage msg = new JpushMessage();			
			msg.setType(JpushMessageType.NOTICE);
			msg.setTitle("百商汇-系统通知");
			msg.setAlert(imgOld.getTitle());
			msg.setContent(imgOld.getContent());
			jmsg.Send(msg);
		}
		return res;
	}

	@Override
	public Integer deleteMessage(int id) {
		return messageDao.deleteByPrimaryKey(id);
	}
}
